<template>
  <div class="refine_userlist">
      <h2 class="titleblue">用户列表</h2>
      <div class="contant">
      <div class="user-title">
        <div @click="createUser" class="fl create" v-if='showCreateBtn'>新建用户</div>
        <div class="fr">
          <label class="sel-label">所属机构</label>
          <el-select clearable v-model="currentOrg" class="select-width-150" placeholder="机构选择" @change="changeOrg">
            <el-option v-for="item in orgList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-select clearable v-model="currentSubOrg" style="margin-right:10px;" class="select-width-150"
                     placeholder="部门选择" @change="searchGroup">
            <el-option v-for="item in subOrgList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-input prefix-icon="el-icon-search" placeholder="搜索用户" v-model="keyword" class="plansearch" clearable
                    @change='search'>
            <template slot="append">搜索</template>
          </el-input>
        </div>
      </div>
      <data-table :page='currentPage' :head="thead" :data="tableData" :actions="['edit','status','del','reset']"
                  @callback="dataAction"></data-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        layout="total,prev, pager, next, jumper"
        :total="dataCount"
        background
      >
      </el-pagination>
    </div>
    <el-dialog title="" :visible.sync="showCreateDialog" width="80%"
               append-to-body @close='closeDialog' @open='showCreateDialog = true'>
      <user-create v-if="showCreateDialog" :user-data="userData" :role-array="roleArray" :org-array="orgList1"
                   @close='closeCreate'></user-create>
    </el-dialog>
  </div>

</template>

<script>
  import DataTable from '@/components/common/DataTable.vue'
  import UserCreate from './UserCreate.vue'
  import * as sysUserService from '@/services/SysUserService.js'
  import * as userRoleService from '@/services/UserRoleService.js'
  import * as orgService from '@/services/OrganizationService.js'

  export default {
      name: 'UserList',
    components: {
      'data-table': DataTable,
      'user-create': UserCreate
    },
    data: function () {
      return {
        keyword: '',
        roleArray: [],
        orgList: [],
        subOrgList: [],
        currentOrg: '',
        currentSubOrg: '',
        userId: 0,
        type: '',
        thead: [
          {name: '执法证号', prop: 'certificateNumber'},
          {name: '用户名', prop: 'username'},
          {name: '姓名', prop: 'fullname'},
          {name: '手机号', prop: 'telephone'},
          {name: '所属部门', prop: 'orgName'},
          {name: '用户角色', prop: 'roleName'},
        ],
        tableData: [],
        options: [{name: '编辑', prop: 'edit'}, {name: '禁用', prop: 'disabled'}, {name: '启用', prop: 'able'}, {
          name: '删除',
          prop: 'del'
        }, {name: '重置密码', prop: 'reset'}],
        currentPage: 1,
        currentPages: 1,
        dataCount: 0,
        showCreateDialog: false,
        showCreateBtn: true,
        userData: null,
          orgList1: []
      }
    },
    created () {
      this.showCreateBtn = this.$checkPermission('/user/create')
      // console.log('org is:::::::', this.$profile.organiza)
      let orgQuery = ''
      // 局领导，海事处，执法大队默认查看本部门的人
      if (this.$profile.organiza.businessOrg === 0 || this.$profile.organiza.businessOrg === 3 || this.$profile.organiza.businessOrg === 4) {
        if (this.$profile.organiza.parentId !== null) {
          orgQuery = 'id=_=' + this.$profile.organiza.parentId + ';parentId=_=' + this.$profile.organiza.parentId
        } else {
          orgQuery = 'id=_=' + this.$profile.organiza.id + ';parentId=_=' + this.$profile.organiza.id
        }
      }
      // console.log('query:::::', orgQuery)
      orgService.findAll(orgQuery).then(data => {
        // console.log('org data')
        data.data.sort((a, b) => {
          if (a.businessOrg < b.businessOrg) {
            return -1
          }
          if (a.businessOrg > b.businessOrg) {
            return 1
          }
          return 0
        })
        this.orgList = data.data
        this.getAll()
      })
        orgService.findAll().then(data => {
            data.data.sort((a, b) => {
                if (a.businessOrg < b.businessOrg) {
                    return -1
                }
                if (a.businessOrg > b.businessOrg) {
                    return 1
                }
                return 0
            })
            this.orgList1 = data.data
        })
    },
    methods: {
      search () {
        this.currentPage = 1
        this.getAll()
      },
      async getAll () {
        // let orgId = this.currentSubOrg || this.currentOrg || 0
        // 机构查询条件
        let orgIdAry = []

        // 已选择了二级机构
        if (this.currentSubOrg) {
          orgIdAry.push(this.currentSubOrg)
        }
        // 已选择一级机构
        else if (this.currentOrg) {
          orgIdAry.push(this.currentOrg)
        }
        // 局领导，海事处，执法大队默认查看本部门的人
        else if (this.$profile.organiza.businessOrg === 0 || this.$profile.organiza.businessOrg === 3 || this.$profile.organiza.businessOrg === 4) {
          let orgId = null
          if (this.$profile.organiza.parentId !== null) {
            orgId = this.$profile.organiza.parentId
          } else {
            orgId = this.$profile.organiza.id
          }
          orgIdAry.push(orgId)
          let org = this.orgList.find(o => o.id === orgId)
          if (org.sub) {
            org.sub.forEach(o => {
              orgIdAry.push(o.id)
            })
          }
        }
        let resp = await sysUserService.searchp(this.keyword, this.currentPage - 1, orgIdAry)
        if (this.roleArray.length === 0) {
          this.roleArray = await userRoleService.findAll()
        }
        resp.data.forEach(u => {
          if (u.organiza && u.organiza.name) u.orgName = u.organiza.name

          let role = this.roleArray.find(r => r.id === u.userRoleId)
          if (role) {
            u.roleName = role.name
          }
        })
        this.dataCount = resp.dataCount
        this.tableData = resp.data.map(d => {
          if (d.userRoles) {
            d.roleName = d.userRoles.map(r => r.name).join(', ')
          }
          return d
        })

      },
      dataAction (param) {
        if (param.action === 'edit') {
          this.showCreateDialog = true
          this.userData = param.data
        } else if (param.action === 'status') {
          let data = param.data
          data.status = data.status === 0 ? 1 : 0
          sysUserService.update(data).then(r => {
            this.$alert(data.status === 0 ? '启用成功' : '禁用成功').then(() => {
              this.getAll()
            })
          })
        } else if (param.action === 'del') {
          sysUserService.del(param.data.id).then(r => {
            this.$alert('删除成功').then(() => {
              this.getAll()
            })
          })
        } else if (param.action === 'reset') {
          this.$confirm('此操作将永久重置该用户密码, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            sysUserService.resetPassword(param.data.id).then(res => {
              this.$alert('重置成功').then(() => {
                this.getAll()
              })
            })
          })
        }
      },
      handleClick (tab, event) {
        this.currentPage = this.currentPage1
        this.getData()
      },
      handleCurrentChange (val) {
        this.currentPage = val
        this.getAll()
      },
      closeCreate () {
        this.showCreateDialog = false
        this.getAll()
      },
      closeDialog () {
        this.showCreateDialog = false
      },
      createUser () {
        this.showCreateDialog = true
        this.userData = null

        // this.$router.push("/index/user/ucreate")
      },
      changeOrg (val) {
        this.subOrgList = []
        for (var i of this.orgList) {
          if (i.id === val && i.sub) {
            this.subOrgList = i.sub
            break
          }
        }
        this.currentPage = 1
        this.getAll()
      },
      searchGroup () {
        this.currentPage = 1
        this.getAll()
      },
      cleared () {
        this.searchGroup()
      },
    }
  }
</script>

<style lang='scss'>
  .refine_userlist {
    width: 100%;
    display: inline-block;

    .inlanselect {
      float: left;
      margin-right: 10px;
    }

    .el-tabs {
      width: 100%;
      margin-top: 20px;
      display: inline-block;
    }

    .el-table tr:nth-child(2n) {
      background: #FAFAFA
    }

    .table {
      margin-top: 20px;
    }

    .user-title {
      width: 100%;
      display: inline-block;
    }
  }
</style>
